
using EmperialApps.WeatherSpark.Data;
using EmperialApps.WeatherSpark.Service.Internal;
using System;
using System.Globalization;

namespace EmperialApps.WeatherSpark.Service {

    /// <summary>Contains information about a forecast.</summary>
    public partial class ForecastInfo {

        private const string LocationFormat = "0.00";

        /// <summary>Initializes a new instance of the <see cref="ForecastInfo"/> class with the specified location.</summary>
        public ForecastInfo( Coordinate location )
            : base( location.Latitude.ToString( LocationFormat ), location.Longitude.ToString( LocationFormat ) ) {
        }


        /// <summary>Gets a value indicating whether <see cref="ForecastUrl"/> points to a forecast at the info's location.</summary>
        /// <value>
        /// True if <see cref="ForecastUrl"/> points to a blob with the info's location;
        /// otherwise, false if the URL is null, an error message, or a redirect to another forecast.
        /// </value>
        public bool HasForecast {
            get {
                string url = this.ForecastUrl;
                if( string.IsNullOrEmpty( url ) || url[0] == '-' )
                    return false;

                Coordinate location = this.GetLocation( );
                string expected = location.GetName( );
                return url.EndsWith( expected );
            }
        }


        /// <summary>Gets the location of the forecast.</summary>
        public Coordinate GetLocation( ) {
            Coordinate location = Coordinate.Parse( this.PartitionKey, this.RowKey, false );
            return location;
        }


        private static string SaveDateTimeOffset( DateTimeOffset value ) {
            return value.ToString( "o", CultureInfo.InvariantCulture );
        }

        private static DateTimeOffset LoadDateTimeOffset( string serializedDate ) {
            return serializedDate == null
                 ? default( DateTimeOffset )
                 : DateTimeOffset.ParseExact( serializedDate, "o", CultureInfo.InvariantCulture );
        }

    }

}
